package kk.controller;

import com.github.pagehelper.PageInfo;
import kk.domain.Permission;
import kk.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    @RequestMapping("/findAll")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ModelAndView findAll(Integer pageNum,Integer pageSize) throws Exception {
        List<Permission> permissionList = permissionService.findAll(pageNum,pageSize);
        PageInfo pageInfo=new PageInfo(permissionList);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("pageInfo",pageInfo);
        modelAndView.setViewName("permission-list");
        return modelAndView;
    }

    @RequestMapping("/save")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public String save(Permission permission) throws Exception {
        permissionService.save(permission);
        return "redirect:/permission/findAll?pageNum=1&pageSize=4";
    }

    @RequestMapping("/findById")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ModelAndView findById(Integer id) throws Exception{
        Permission permission = permissionService.findById(id);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("permission",permission);
        modelAndView.setViewName("permission-show");
        return modelAndView;
    }

    @RequestMapping("/deleteById")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public String deletePermission(Integer id) throws Exception {
        permissionService.deleteById(id);
        return "redirect:/permission/findAll?pageNum=1&pageSize=4";
    }


    @RequestMapping("/deleteSelectedPermission")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public String deleteSelectedPermission(int[] ids) throws Exception{
        for (int id : ids) {
            permissionService.deleteById(id);
        }
        return "redirect:/permission/findAll?pageNum=1&pageSize=4";
    }
}
